package com.heying.springcore.aop.transaction;

import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

@Component
@Aspect //添加切面，添加事务
public class Transaction {

//    private Connection conn;

    //ThreadLocal的作用，多线程
    private ThreadLocal<Connection> tl = ThreadLocal.withInitial(()->{
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/test02?userSSL=false&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8";
            return DriverManager.getConnection(url, "root","");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    });

    @Pointcut("execution (* com.heying.springcore.aop.transaction.UserService.addTwoUsers(..))")
    public void transaction(){
    }

    public Transaction() {

    }

    public ThreadLocal<Connection> getTl() {
        return tl;
    }

    public void setTl(ThreadLocal<Connection> tl) {
        this.tl = tl;
    }

    //开启事务
    @Before("transaction()")
    public void begin() throws SQLException {
        System.out.println("------开启事务--------");
        System.out.println(Thread.currentThread()+"-"+tl.get());
        tl.get().setAutoCommit(false);
    }

    //事务提交
    @AfterReturning("transaction()")
    public void commit() throws SQLException {
        tl.get().commit();
       tl.get().close();

    }

    //事务回退
    @AfterThrowing("transaction()")
    public void rollback() throws SQLException {
        tl.get().rollback();
        tl.get().close();
    }
}
